<?php
// +----------------------------------------------------------------------
// | 幕小铺
// +----------------------------------------------------------------------
// | 版权所有 2016~2019 幕小铺科技（大连）有限公司 [ http://www.XXX.com ]
// +----------------------------------------------------------------------
// | 2020/03/14 jason wang
// +----------------------------------------------------------------------
namespace app\erp\logic;
use app\erp\model\ErpCoupon;
use app\erp\model\ErpCouponUseinfo;
use think\facade\Hook;
use think\DB;
use util\Tree;
use think\facade\Debug;
use think\facade\Cache;
/**
 * 优惠券管理
 * @package app\erp\model
 */
class Couponlogic{

    /**
     * 首页
     * @author  dou<51779987@qq.com>
     * @return array_out(code, message, data)
     */
    public function coupon_list($user_id, $coupon_id = 0, $coupon_isuse = 0){
        DB::startTrans();//启动事务
        try{
            /********行为参数赋值（*）********/
            $params = [
				'user_id'  => $user_id,
            ];
            /********行为参数赋值（*）********/
     
            /********前置行为********/
            $hook_rel = logic_hook($action = __FUNCTION__, $params, 'before');
            if($hook_rel['code'] < 0){
                DB::rollback();
                return array_out(-1002, $hook_rel['message']);//前置错误 -1002
            }
            /********前置行为********/

            /********业务逻辑********/
			//规则表可用的优惠券
			if($coupon_id == 0){
				$map = [];
				$map['coupon_rule']= 1;
				$map['coupon_rule_isuse'] = 1;
				$coupon_rule_id =  model('erp/ErpCouponRules') -> where($map) -> order('id desc') -> column('coupon_id');
			}else{
				$coupon_rule_id = $coupon_id;
			}
			$map = [];
			if($coupon_isuse == 0) $map[] = ['coupon_isuse', '=', 1];		  //是否可用
			$map[] = ['coupon_claim_status', '=', 0]; //是否发完
			$map[] = ['id', 'in', $coupon_rule_id];   // 设置了发放规则
			
			$map1 = $map2 = $map;
			
			$map1[] = ['coupon_period', '=', 0]; //永久有效
			$map1[] = ['coupon_period_etime', '=', 0];
			
			$map2[] = ['coupon_period', '=', 1]; //有效期
			if($coupon_isuse == 0) $map2[] = ['coupon_period_etime', '>', time()];
			
			$list =  model('erp/ErpCoupon') -> whereOr([$map1, $map2]) -> order('id desc') -> select();

			$result_list = [];
            foreach($list as $key => $value){
				$map = [
					['coupon_id', '=', $value['id']],
				];
				$cpupon_count1 = model('erp/ErpCouponUseinfo', 'model') -> where($map) -> where('coupon_user','>',0) -> count();//已领取数量
				$cpupon_count2 = intval($value['coupon_sum'] - $cpupon_count1);//未领取数量
				
				$receive_count = model('erp/ErpCouponUseinfo') ->  where($map) -> where('coupon_user', $user_id) -> count();//是否领取
				$is_receive = $receive_count > 0 ? 1: 0; // 1领过 0可领

				if($value['coupon_attribute'] == 1 && $value['coupon_attribute_num'] > $receive_count){ //可重复领取 判断是否达到 领取上限
					$is_receive = 0;
				}
				$rel_list['id'] 					= (int)$value['id'];
				$rel_list['couponName'] 			= (string)$value['coupon_name'];
				$rel_list['couponValue'] 			= (string)sprintf("%.2f", $value['coupon_value']);
				$rel_list['couponType'] 			= (int)$value['coupon_type'];
				$rel_list['couponPeriod'] 			= (int)$value['coupon_period'];
				$rel_list['couponPeriodStime'] 		= (int)$value['coupon_period_stime'];
				$rel_list['couponPeriodEtime'] 		= (int)$value['coupon_period_etime'];
				$rel_list['couponUseCondition'] 	= (int)$value['coupon_use_condition'];
				$rel_list['couponUseConditionNum'] 	= (string)$value['coupon_use_condition_num'];
				$rel_list['couponSum'] 				= (int)$value['coupon_sum'];
				$rel_list['couponIsuse'] 			= (int)$value['coupon_isuse'];
				$rel_list['couponSumGet'] 			= (int)$cpupon_count1;
				$rel_list['couponSumUnget'] 		= (int)$cpupon_count2;
				$rel_list['isReceive'] 				= $is_receive;
				$rel_list['couponRule'] 			= '';
				$rel_list['coupon_attribute'] 		= (int)$value['coupon_attribute'];
				$rel_list['coupon_attribute_num'] 	= (int)$value['coupon_attribute_num'];
				
				if($cpupon_count2 > 0 && $coupon_id == 0){
					$result_list[] = $rel_list;
				}
				if($coupon_id != 0){
					$result_list[$key] = $rel_list;
				}
			}
			$isReceive_list = array_column($result_list, 'isReceive');
			array_multisort($isReceive_list, SORT_ASC, $result_list);

            /********业务逻辑********/
			
            /********后置行为********/
            $hook_rel = logic_hook($action = __FUNCTION__, $params, 'after');
            if($hook_rel['code'] < 0){
                DB::rollback();
                return array_out(-1003, $hook_rel['message']);//后置错误 -1003
            }
            /********后置行为********/

            /********逻辑返回********/
			DB::commit();
            return array_out(200, 'success', $result_list);
            /********逻辑返回********/
			
        } catch (\Exception $e) {
			DB::rollback();
            return array_out(-9999, $e -> getMessage());//异常错误 -9999
        }
    }

    /**
     * 添加
     * @param coupon_name 	            string      优惠券名称
     * @param coupon_value 		        string      折扣券价值
     * @param coupon_rule 		        tinyint     发放规则(0自动;1手动)
     * @param coupon_claim_status 		string      发放状态(0未发放;1已发放;)
     * @param coupon_type 		        text        折扣券类型(1代金券)
     * @param coupon_source 	        string      来源(1线上)
     * @param coupon_period_stime 		int         有效开始时间
     * @param coupon_period_etime 		int         有效截止时间
     * @param coupon_sum 				int         生成数量
     * @param coupon_attribute 			tinyint     属性(0不重复;1可重复)
     * @param coupon_use_condition 		tinyint     使用条件(0无条件;)
     * @param coupon_use_scope 			tinyint     使用范围(0全站;)
     * @param coupon_use_scope_info 	text        使用范围详情
     * @param coupon_isuse 			    tinyint     是否可用(0可用;1不可用)
     * @param create_time 				int         创建时间
     * @param update_time 				int         编辑时间
     * @author dou<51779987@qq.com>
     * @return array_out(code, message, data)
     */
    public function add($user_id, $coupon_name, $coupon_value, $coupon_claim_status, $coupon_type, $coupon_source,$coupon_period, $coupon_period_stime, $coupon_period_etime, $coupon_sum, $coupon_attribute, $coupon_attribute_num, $coupon_use_condition, $coupon_use_condition_num, $coupon_use_scope, $coupon_use_scope_info,$coupon_isuse){
        DB::startTrans();//启动事务
        try{
            /********行为参数赋值（*）********/
            $params = [
				//'user_id' 	            => $user_id,
				'coupon_name'               => $coupon_name,
                'coupon_value'              => $coupon_value,
 /*               'coupon_rule' 	        => $coupon_rule,
                'coupon_rule_type' 	        => $coupon_rule_type,*/
                'coupon_claim_status'       => $coupon_claim_status,
                'coupon_type' 	            => $coupon_type,
				'coupon_source' 	            => $coupon_source,
				'coupon_period' 	        => $coupon_period,
				'coupon_period_stime' 	    => $coupon_period_stime,
				'coupon_period_etime' 	    => $coupon_period_etime,
				'coupon_sum' 	            => $coupon_sum,
				'coupon_attribute' 	    	=> $coupon_attribute,
				'coupon_attribute_num' 	    => $coupon_attribute_num,
				'coupon_use_condition' 	    => $coupon_use_condition,
				'coupon_use_condition_num' 	=> $coupon_use_condition_num,
				'coupon_use_scope' 	    	=> $coupon_use_scope,
				'coupon_use_scope_info' 	=> $coupon_use_scope_info,
				'coupon_isuse' 	    	    => $coupon_isuse,
            ];
            /********行为参数赋值（*）********/
     
            /********前置行为********/
            $hook_rel = logic_hook($action = __FUNCTION__, $params, 'before');
            if($hook_rel['code'] < 0){
                DB::rollback();
                return array_out(-1002, $hook_rel['message']);//前置错误 -1002
            }
            /********前置行为********/

			$rel_coupon = model('ErpCoupon') -> addData($coupon_name, $coupon_value, $coupon_claim_status, $coupon_type, $coupon_source, $coupon_period,$coupon_period_stime, $coupon_period_etime, $coupon_sum, $coupon_attribute, $coupon_attribute_num, $coupon_use_condition, $coupon_use_condition_num, $coupon_use_scope, $coupon_use_scope_info,$coupon_isuse);//添加
            if($rel_coupon['code'] < 0){
                DB::rollback();
                return array_out(-1005, 'error');//添加失败 返回-1005,error
            }else{
                //更新代金券使用表---按照分发数量
                $useInfo = [];
                $code_count = model('ErpCouponUseinfo') ->count();//获取数量
                for($i = 1; $i <= $coupon_sum; $i++){
                    $useInfo[$i]['coupon_id'] = $rel_coupon['data'];
                    $useInfo[$i]['coupon_code'] = 'CPN'.date('Ymd').(str_pad(($code_count+$i),5,"0",STR_PAD_LEFT));
                    $useInfo[$i]['coupon_stime'] = $coupon_period_stime;
                    $useInfo[$i]['coupon_etime'] = $coupon_period_etime;
                    $useInfo[$i]['coupon_use_type'] = 0;
                }
                $rel = model('ErpCouponUseinfo') -> saveAll($useInfo, false);//添加
                if(!$rel){
                    DB::rollback();
                    return array_out(-1005, 'error1');//添加失败 返回-1005,error
                }else{}
            }
			
            /********业务逻辑********/

            /********后置行为********/
            $hook_rel = logic_hook($action = __FUNCTION__, $params, 'after');
            if($hook_rel['code'] < 0){
                DB::rollback();
                return array_out(-1003, $hook_rel['message']);//后置错误 -1003
            }
            /********后置行为********/

            /********逻辑返回********/
			DB::commit();
            return array_out(200, 'success');
            /********逻辑返回********/
			
        } catch (\Exception $e) {
			DB::rollback();
            return array_out(-9999, $e -> getMessage());//异常错误 -9999
        }
    }

    /**
     * 编辑
     * @param id 	            string  供应商名称
     * @param coupon_name 	            string      优惠券名称
     * @param coupon_value 		        string      折扣券价值
     * @param coupon_rule 		        tinyint     发放规则(0自动;1手动)
     * @param coupon_claim_status 		string      发放状态(0未发放;1已发放;)
     * @param coupon_type 		        text        折扣券类型(1代金券)
     * @param coupon_source 	        string      来源(1线上)
     * @param coupon_period_stime 		int         有效开始时间
     * @param coupon_period_etime 		int         有效截止时间
     * @param coupon_sum 				int         生成数量
     * @param coupon_attribute 			tinyint     属性(0不重复;1可重复)
     * @param coupon_use_condition 		tinyint     使用条件(0无条件;)
     * @param coupon_use_scope 			tinyint     使用范围(0全站;)
     * @param coupon_use_scope_info 	text        使用范围详情
     * @param coupon_isuse 			    tinyint     是否可用(0可用;1不可用)
     * @param create_time 				int         创建时间
     * @param update_time 				int         编辑时间
     * @author dou<51779987@qq.com>
     * @return array_out(code, message, data)
     */
    public function edit($id, $user_id, $coupon_name, $coupon_value, $coupon_claim_status, $coupon_type, $coupon_source, $coupon_period, $coupon_period_stime, $coupon_period_etime, $coupon_sum, $coupon_attribute,$coupon_attribute_num, $coupon_use_condition, $coupon_use_condition_num, $coupon_use_scope, $coupon_use_scope_info,$coupon_isuse,$coupon_sum_need){
        DB::startTrans();//启动事务
        try{
            /********行为参数赋值（*）********/
            $params = [
                //'user_id' 	            => $user_id,
                'id' 	                    => $id,
                'coupon_name'               => $coupon_name,
                'coupon_value'              => $coupon_value,
/*                'coupon_rule' 	        => $coupon_rule,
                'coupon_rule_type' 	        => $coupon_rule_type,*/
                'coupon_claim_status'       => $coupon_claim_status,
                'coupon_type' 	            => $coupon_type,
                'coupon_source' 	        => $coupon_source,
                'coupon_period' 	        => $coupon_period,
                'coupon_period_stime' 	    => $coupon_period_stime,
                'coupon_period_etime' 	    => $coupon_period_etime,
                'coupon_sum' 	            => $coupon_sum,
                'coupon_attribute' 	    	=> $coupon_attribute,
                'coupon_attribute_num' 	    => $coupon_attribute_num,
                'coupon_use_condition' 	    => $coupon_use_condition,
                'coupon_use_condition_num' 	=> $coupon_use_condition_num,
                'coupon_use_scope' 	    	=> $coupon_use_scope,
                'coupon_use_scope_info' 	=> $coupon_use_scope_info,
                'coupon_isuse' 	    	    => $coupon_isuse,
            ];

            /********行为参数赋值（*）********/

            /********前置行为********/
            $hook_rel = logic_hook($action = __FUNCTION__, $params, 'before');
            if($hook_rel['code'] < 0){
                DB::rollback();
                return array_out(-1002, $hook_rel['message']);//前置错误 -1002
            }
            /********前置行为********/

            /********业务逻辑********/
			$rel_coupon = model('ErpCoupon') -> editData($id, $coupon_name, $coupon_value, $coupon_claim_status, $coupon_type, $coupon_source,$coupon_period, $coupon_period_stime, $coupon_period_etime, $coupon_sum, $coupon_attribute,$coupon_attribute_num, $coupon_use_condition, $coupon_use_condition_num, $coupon_use_scope, $coupon_use_scope_info,$coupon_isuse);

            if($rel_coupon['code'] == 200){
                if($coupon_sum_need > 0){
                    //更新代金券使用表---按照分发数量
                    $useInfo = [];
                    $code_count = model('ErpCouponUseinfo') ->count();//获取已有的数量
                    for($i = 1; $i <= $coupon_sum_need; $i++){
                        $useInfo[$i]['id'] = '';
                        $useInfo[$i]['coupon_id'] = $id;
                        $useInfo[$i]['coupon_code'] = 'CPN'.date('Ymd').(str_pad(($code_count+$i),5,"0",STR_PAD_LEFT));
                        $useInfo[$i]['coupon_stime'] = $coupon_period_stime;
                        $useInfo[$i]['coupon_etime'] = $coupon_period_etime;
                        $useInfo[$i]['coupon_use_type'] = 0;
                    }
                    $rel = model('ErpCouponUseinfo') -> saveAll($useInfo, false);//添加
                }else{}
                //批量更新时间
                $data['coupon_stime'] = $coupon_period_stime;
                $data['coupon_etime'] = $coupon_period_etime;
                $rel = model('ErpCouponUseinfo')->update($data, ['coupon_id'=>$id]);
            }else{
                DB::rollback();
                return array_out(-1005, 'error');//添加失败 返回-1005,error
            }
            /********业务逻辑********/
			
            /********后置行为********/
            $hook_rel = logic_hook($action = __FUNCTION__, $params, 'after');
            if($hook_rel['code'] < 0){
                DB::rollback();
                return array_out(-1003, $hook_rel['message']);//后置错误 -1003
            }
            /********后置行为********/

            /********逻辑返回********/
			DB::commit();
            return array_out(200, 'success');
            /********逻辑返回********/
			
        } catch (\Exception $e) {
			DB::rollback();
            return array_out(-9999, $e -> getMessage());//异常错误 -9999
        }
    }

    /**
     * 删除
     * @param int $id
     * @author dou<51779987@qq.com>
     * @return bool
     */
    public function delete($user_id, $id){
        DB::startTrans();//启动事务
        try{
            /********行为参数赋值（*）********/
            $params = [
				'user_id' 	=> $user_id,
				'id' 		=> $id,
            ];
            /********行为参数赋值（*）********/
     
            /********前置行为********/
            $hook_rel = logic_hook($action = __FUNCTION__, $params, 'before');
            if($hook_rel['code'] < 0){
                DB::rollback();
                return array_out(-1002, $hook_rel['message']);//前置错误 -1002
            }
            /********前置行为********/

            /********业务逻辑********/
			$rel = model('ErpCoupon') -> deleteData($id);
			if($rel['code'] < 0){
				return array_out(-1005, 'error');//删除失败 返回-1005,error
			}
			
            /********业务逻辑********/
			
            /********后置行为********/
            $hook_rel = logic_hook($action = __FUNCTION__, $params, 'after');
            if($hook_rel['code'] < 0){
                DB::rollback();
                return array_out(-1003, $hook_rel['message']);//后置错误 -1003
            }
            /********后置行为********/

            /********逻辑返回********/
			DB::commit();
            return array_out(200, 'success');
            /********逻辑返回********/
			
        } catch (\Exception $e) {
			DB::rollback();
            return array_out(-9999, $e -> getMessage());//异常错误 -9999
        }
    }
}